<template>
  <div class="search-view">
    <div class="search-btn">
      <el-button @click="search">拉框查询</el-button>
    </div>
    <div class="search-table" v-show="tableData.length > 0">
      <el-table :data="tableData" @row-click="handleRowClick">
        <el-table-column prop="event_num" label="事件编号" />
        <el-table-column prop="level" label="事件级别" />
        <el-table-column prop="area" label="事故区域" />
        <el-table-column prop="name" label="事件类型" />
        <el-table-column prop="car_num" label="车牌号码" />
        <el-table-column prop="phone" label="联系电话" />
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { onMounted, inject, ref, onBeforeUnmount } from 'vue'
import { getWuhanEvents } from '@/api';
import { DrawRect } from '@antv/l7-draw';
import { pointsWithinPolygon } from '@turf/turf'
import { PointLayer } from '@antv/l7'
import { center } from '@turf/turf';
const { map, scene } = inject('mapScene')
let eventDate = ref([])
let tableData = ref([])
let draw
let pointLayer
onMounted(async () => {
  map.flyTo({
    center: [114.406325, 30.465113],
    zoom: 15,
    pitch: 45,
  })
  const { data: event } = await getWuhanEvents()
  eventDate.value = event
});
function search() {
  // 添加交互画笔
  if (draw) {
    draw.clear()
    draw.destroy()
    draw = null
  }
  if (tableData.value.length > 0) {
    tableData.value = []
  }
  if (pointLayer) {
    scene.removeLayer(pointLayer)
    pointLayer = null
  }
  draw = new DrawRect(scene, {
  })
  draw.enable()
  draw.on('add', (e) => {
    let result = pointsWithinPolygon(eventDate.value, e)

    pointLayer = new PointLayer({
      name: '事故点',
    });
    pointLayer.source(result)
      .size(20)
      .color('pink')
      .shape('circle')
      .active(true)
      .animate(true)
    scene.addLayer(pointLayer)
    tableData.value = result.features.map((item) => {
      return {
        ...item.properties,
        center: item.geometry.coordinates,
      }

    })
    console.log(tableData.value)
  })
}
function handleRowClick(row) {
  if (draw) {
    draw.destroy()
    draw = null
  }
  let center = row.center
  map.flyTo({
    center,
    zoom: 10,
    pitch: 0,
  })
}
onBeforeUnmount(() => {
  if (draw) {
    draw.destroy()
    draw = null
  }
  if (pointLayer) {
    scene.removeLayer(pointLayer)
    pointLayer = null
  }
  if (tableData.value.length > 0) {
    tableData.value = []
  }
})



</script>

<style scoped lang="scss">
.search-view {
  .search-btn {
    position: fixed;
    top: 200px;
    right: 60px;
  }

  .search-table {
    position: fixed;
    width: 60%;
    bottom: 100px;
    left: 20%;
    z-index: 1000;
  }

  .el-table {
    max-height: 300px;
    overflow-y: scroll;

  }

  :deep(.el-table_cell) {
    background-color: #ccc;
  }
}
</style>
